package com.xlh.Utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by fang on 2018-01-16.
 */

public class DataBaseHelper extends SQLiteOpenHelper {


    private static final String DATABASE_NAME="wzdata.db";//数据库名称
    private static final int SCHEMA_VERSION=2;//版本号,则是升级之后的,升级方法请看onUpgrade方法里面的判断
    public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DataBaseHelper.DATABASE_NAME, null, DataBaseHelper.SCHEMA_VERSION);
    }

    /**
     * 注意！！onCreate 不能写建表语句
     * 为什么自己百度！
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {


       // db.execSQL("CREATE TABLE loginLog (id INTEGER PRIMARY KEY AUTOINCREMENT, username varchar(20), password varchar(20));");

    }

    @Override
    public void onOpen(SQLiteDatabase db) {

        super.onOpen(db);
        //自定义按钮
        if( checkTable(db,"button_cmds") <=0){
            db.execSQL("CREATE TABLE button_cmds (id INTEGER PRIMARY KEY AUTOINCREMENT, parent_but_key varchar(20), butkey varchar(20), cmds TEXT);");
        }
        //登录记录
        if( checkTable(db,"login_log") <=0){
            db.execSQL("CREATE TABLE login_log (id INTEGER PRIMARY KEY AUTOINCREMENT, username varchar(20), password varchar(20));");
        }
        //配色
        if( checkTable(db,"color_conf") <=0){
            db.execSQL("CREATE TABLE color_conf (id INTEGER PRIMARY KEY AUTOINCREMENT, tagname varchar(20), colorstr TEXT);");
        }


    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        return;
    }

    public int checkTable(SQLiteDatabase db,String tn){

        Cursor c = null;
        int i=0;
        try{
           c = db.rawQuery("select * from sqlite_master where type='table' and name=?",new String[]{tn});
            i = c.getCount();
        }catch (Exception e){
            Log.e("database","checkTable error" + e.getMessage()) ;
        }finally{
            if(null != c && !c.isClosed()){
                c.close() ;
            }
        }
        return i;

    }


}
